<template>
  <div class="cont">
    <van-pull-refresh
      v-model="getUserLoading"
      @refresh="getUsers(true)"
      class="pull-refresh"
    >
      <van-dropdown-menu>
        <van-dropdown-item v-model="sortRoleVal" :options="sortRole" />
        <van-dropdown-item
          v-model="sortCreateTimeVal"
          :options="sortCreateTime"
        />
      </van-dropdown-menu>
      <van-search v-model="searchVal" placeholder="输入用户id或昵称进行搜索" />
      <van-skeleton title avatar :row="10" :loading="skeletonLoading">
        <van-swipe-cell v-for="(item, index) in users" :key="index">
          <van-card
            :desc="'id:' + item.id"
            :title="'昵称:' + (item.picname ? item.picname : '未设置')"
            class="goods-card"
            :thumb="
              item.pic
                ? item.pic
                : Tools.getImageUrl('../../assets/avatar_default.jpg')
            "
          >
            <template #tags>
              <van-tag plain type="warning">{{
                getRoleName(item.role)
              }}</van-tag>
            </template>
          </van-card>
          <template #right>
            <van-button
              square
              text="编辑"
              type="primary"
              class="delete-button"
            />
            <van-button
              square
              text="删除"
              type="danger"
              class="delete-button"
            />
          </template>
        </van-swipe-cell>
      </van-skeleton>
    </van-pull-refresh>
    <div class="control-area">
      <van-row>
        <van-col :span="16">
          <!-- 分页器 -->
          <van-pagination
            v-model="page"
            :total-items="count"
            :items-per-page="size"
            :show-page-size="4"
            @change="pageChange"
          />
        </van-col>
        <van-row :span="6">
          <van-button icon="plus" type="primary" @click="addUserShow = true"
            >添加用户</van-button
          >
        </van-row>
      </van-row>
    </div>
  </div>
  <!-- 弹出框 添加用户 -->
  <van-dialog
    v-model:show="addUserShow"
    title="添加用户"
    :show-confirm-button="false"
  >
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="createUserForm.id"
          name="id"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="createUserForm.pd"
          type="password"
          name="pd"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <van-field
          v-model="createUserForm.email"
          type="email"
          name="email"
          label="邮箱"
          placeholder="邮箱"
          :rules="[{ required: true, message: '请填写邮箱' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-row>
          <van-col :span="11">
            <van-button
              round
              block
              plain
              type="primary"
              @click="addUserShow = false"
              >取消添加</van-button
            >
          </van-col>
          <van-col :span="11" :offset="2">
            <van-button
              round
              block
              type="primary"
              native-type="submit"
              @click="handlerRegister"
            >
              添加用户
            </van-button>
          </van-col>
        </van-row>
      </div>
    </van-form>
  </van-dialog>
</template>

<script setup>
import { Tools } from "../../utils/Tools";
import { ref, getCurrentInstance, reactive } from "vue";
import { AllRequest } from "../../utils/allRequest";
const { proxy } = getCurrentInstance();
const sortRoleVal = ref(0);
const searchVal = ref(null);
const sortCreateTimeVal = ref(0);
const page = ref(1);
const size = ref(5);
const users = ref([]);
const count = ref(0);
const getUserLoading = ref(false);
const createUserForm = reactive({
  id: "",
  pd: "",
  email: "",
});
const sortRole = ref([
  {
    value: 0,
    text: "没有角色数据",
  },
]); // 角色筛选的数据
const sortCreateTime = ref([
  // 按注册时间筛选选项
  {
    value: 0,
    text: "注册时间倒序",
  },
  {
    value: 1,
    text: "注册时间正序",
  },
  {
    value: 2,
    text: "登录时间倒序",
  },
  {
    value: 4,
    text: "登录时间正序",
  },
]);
const skeletonLoading = ref(true); // 骨架框
const addUserShow = ref(false); // 添加用户

initData();
/* 工具函数 */

/* 初始化函数 */
async function initData() {
  await Promise.all([getRoles(), getUsers()]);
  skeletonLoading.value = false; // 骨骼条关闭
}

/* 加载用户方法 */
async function getUsers(_refresh = false) {
  if (_refresh) {
    getUserLoading.value = true;
  }
  await AllRequest.getUsers(page.value, size.value).then((res) => {
    if (res.data.code == 2000) {
      users.value = res.data.data;
      count.value = res.data.count;
    } else {
      Tools.showMessage("用户数据失败!请检查网络或服务器状态。", "warning");
    }
    if (_refresh) {
      getUserLoading.value = false;
    }
  });
}

/* 加载角色方法 */
async function getRoles() {
  await proxy.$store.roles.then((res) => {
    if (res.data.code != 2000) {
      Tools.showMessage("获取角色数据失败!请检查网络或服务器状态。", "warning");
    } else {
      sortRole.value = res.data.data.map((item, index) => {
        const { role_id, role_name } = item;
        let newItem = { value: role_id, text: role_name };
        return newItem;
      });
      sortRole.value.unshift({ value: null, text: "全部" });
      sortRoleVal.value = null;
    }
  });
}

/* 指定角色id加载角色名 */

function getRoleName(_roleId) {
  return Tools.filterArrVal(sortRole.value, "value", _roleId, "text");
}

/* 当页码被切换 */
function pageChange(_page) {
  page.value = _page;
  getUsers(); // 刷新用户
}

/* 添加用户请求 */
function handlerRegister() {
  AllRequest.register(createUserForm).then((res) => {
    if (res.data.code != 2000) {
      Tools.showMessage(res.data.msg, "warning");
    } else {
      Tools.showMessage("添加用户成功!");
      addUserShow.value = false;
      getUsers(); // 刷新用户
    }
  });
}
</script>

<style scoped>
.cont {
  /* 容器 */
  height: 90vh;
  position: relative;
}
.goods-card {
  margin: 0;
  background-color: #fff;
}

.delete-button {
  height: 100%;
}
.control-area {
  width: 100%;
}

.pull-refresh {
  /* 下拉刷新 */
  height: calc(90vh - 0.7rem);
}
</style>